/*
  這是從 Console 隱藏 User 輸入字元，以取得密碼的小程式。
*/
package idv.jieh.commons.io;

import java.io.*;

public class PasswordField extends idv.jieh.commons.comm.BasicClass{

  public String getPassword(String prompt) throws IOException {
    MaskingThread masking = new MaskingThread(prompt);
    new Thread(masking).start();

    String password = "";
    while (true) {
      char c = (char)System.in.read();
      // assume enter pressed, stop masking
      masking.stopMasking();

      if (c == '\r') {
        c = (char)System.in.read();
        if (c == '\n') break; else continue;
      } else if (c == '\n') {
        break;
      } else {
        password += c; // store the password
      }
    }

    return password;
  }

  //******** Class MaskingThread Start ********//
  private class MaskingThread extends Thread {
    private String prompt;
    private boolean stop = false;

    private MaskingThread(String str){ prompt = str; }

    public void run() {
      while(!stop) {
        try {
          super.sleep(1);
        }catch (InterruptedException ex) { ex.printStackTrace(); }

        if (!stop) System.out.print("\r" + prompt + " \r" + prompt);
        System.out.flush();
      }
    }

    private void stopMasking() { this.stop = true; }

  }
  //******** Class MaskingThread End ********//

}
